#!/usr/bin/python3
# 2016.11.18 尝试搞GUI
# -*- coding:utf-8 -*-
#
import datetime
import os
import sys
import threading
import tkinter
import tkinter.filedialog
from tkinter import messagebox
import multidivid


# 重载的多线程
class forTkinter(threading.Thread):
    def __init__(self, file, outdir, num, thread):
        threading.Thread.__init__(self)
        self.file = file
        self.outdir = outdir
        self.num = num
        self.thread = thread

    def run(self):
        multidivid.main(file=self.file, output=self.outdir, num=self.num, thread=self.thread)


def main():

    # 用来给界面上的按钮赋值的
    def openFile():         # 打开文件
        r = tkinter.filedialog.askopenfilename(title="输入文件", filetypes=[('文本文件', '.txt'), ('All files', '*')])
        infile.set(str(r))
        return r

    def FileSave():         # 设置保存目录
        r = tkinter.filedialog.askdirectory(title="输出目录")
        outdir.set(r)
        return r

    def getNum():           # 用来返回线程数
        lie = num.get()
        if not lie or lie <= 0:
            lie = 0
        else:
            lie = num.get()-1
        return lie

    def getThread():        # 用来返回进程数
        num = thread.get()
        if not num or num <= 0:
            num = 1
        return num

    def runButton():         # 真正运行的模式
        begin = datetime.datetime.now()
        if not infile.get() and not outdir.get():
            messagebox.showinfo('错误', '没有任何输入')
        elif not infile.get() and outdir.get():
            messagebox.showinfo('错误', '没有输入文件')
        elif infile.get() and not outdir.get():
            messagebox.showinfo('错误', '没有输出文件夹')
        else:
            waitButton.config(stat=tkinter.NORMAL)
            p = forTkinter(file=infile.get(), outdir=outdir.get(), num=getNum(), thread=getThread())
            p.start()
            runButton.config(text='等着吧', stat=tkinter.DISABLED)
            p.join()
            end = datetime.datetime.now()
            runtime = str(end - begin)
            messagebox.showinfo('已完成', "共计运行" + runtime)
            runButton.config(text='开始', stat=tkinter.NORMAL)

    def wait():
        evt.clear()
        keepButton.config(stat=tkinter.NORMAL)
        waitButton.config(stat=tkinter.DISABLED)

    def conti():
        evt.set()
        keepButton.config(stat=tkinter.DISABLED)
        waitButton.config(stat=tkinter.NORMAL)

    def shuoming():
        messagebox.showinfo('说明', '功能很单一\n按照文件的某一列内容的不同\n将该文件分成不同的子文件')

    def about():
        messagebox.showinfo('关于', '学习Python练手的第一个GUI程序\n\t张一鸣\t\n于2016.11.19')

    # 重中之重，用来解决打包找不到图片的问题
    def resource_path(relative_path):
        """ Get absolute path to resource, works for dev and for PyInstaller """
        try:
            # PyInstaller creates a temp folder and stores path in _MEIPASS
            base_path = sys._MEIPASS
        except Exception:
            base_path = os.path.abspath(".")

        return os.path.join(base_path, relative_path)


    root = tkinter.Tk()
    # 主窗口的设置
    root.title("测试学习")
    root.geometry("800x500+200+200")
    root.resizable(width=False, height=False)
    # 初始化变量
    text = tkinter.StringVar()
    infile = tkinter.StringVar()
    outdir = tkinter.StringVar()
    num = tkinter.IntVar()
    num.set(1)
    thread = tkinter.IntVar()
    thread.set(1)
    evt = threading.Event()
    # 添加菜单
    menu = tkinter.Menu(root)
    submenu=tkinter.Menu(menu, tearoff=0)
    submenu.add_command(label="打开", command=openFile, accelerator='Ctrl+N')
    submenu.add_command(label="保存", command=FileSave)
    submenu.add_separator()                 # 添加分隔线
    submenu.add_command(label="退出", command=root.quit)
    menu.add_cascade(label="文件", menu=submenu)
    submenu=tkinter.Menu(menu, tearoff=0)   # 新建子菜单
    submenu.add_command(label="说明", command=shuoming)
    submenu.add_command(label="关于", command=about)
    menu.add_cascade(label="帮助", menu=submenu)
    root.config(menu=menu)                  # 在窗口中设置菜单
    # 添加输入框
    inputL=tkinter.Label(root, text="输入文件")
    inputL.place(x=50, y=50,
                 width=150, height=30)
    inputE=tkinter.Entry(root, textvariable=infile)
    inputE.place(x=250, y=50,
                 width=300, height=30)
    inputB=tkinter.Button(root, text="打开", command=openFile)
    inputB.place(x=600, y=50,
                 width=60, height=30)
    # 输出文件的各种框
    outputL=tkinter.Label(root, text="输出文件")
    outputL.place(x=50, y=100,
                 width=150, height=30)
    outputE=tkinter.Entry(root, textvariable=outdir)
    outputE.place(x=250, y=100,
                 width=300, height=30)
    outputB=tkinter.Button(root, text="输出", command=FileSave)
    outputB.place(x=600, y=100,
                 width=60, height=30)

    # 这是添加是否需要输入列数和进程数
    numL=tkinter.Label(root, text="列：")
    numL.place(x=100, y=150,
                 width=50, height=30)

    numE=tkinter.Entry(root, textvariable=num)
    numE.place(x=200, y=150,
                 width=100, height=30)
    # 进程数
    threadL = tkinter.Label(root, text="进程数：")
    threadL.place(x=400, y=150,
               width=50, height=30)

    threadE = tkinter.Entry(root, textvariable=thread)
    threadE.place(x=500, y=150,
               width=100, height=30)

    # 添加一个run按钮
    runButton=tkinter.Button(root, text="运行", command=runButton)
    runButton.place(relx=0.7, y=200,
                    width=100, height=50)

    # 添加一个暂停按钮
    waitButton = tkinter.Button(root, text="暂停", command=wait, stat=tkinter.DISABLED)
    waitButton.place(relx=0.4, y=200,
                    width=100, height=50)

    # 添加一个继续按钮
    keepButton = tkinter.Button(root, text="继续", command=conti, stat=tkinter.DISABLED)
    keepButton.place(relx=0.1, y=200,
                    width=100, height=50)

    # 动作绑定
    root.bind_all("<Control-n>", lambda event:openFile())

    # 添加一个图形
    image = tkinter.Canvas(root, width=400, height=250)
    im = tkinter.PhotoImage(file=resource_path(os.path.join('0.gif')))          # 为了解决打包找不到图片的问题，这里也调整过了
    image.create_image(100, 150, image=im)
    image.create_text(300, 180, text='练手测试而已', fill='red', font=("宋体", 20, "normal"))
    image.place(relx=0.2, rely=0.5)

    # 添加一个text窗口
    root.mainloop()

if __name__ == "__main__":
    main()
